//
//  QuestionViewController.m
//  Stock
//
//  Created by sun black on 11-12-13.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "QuestionViewController.h"
#import "CommonUtil.h"
#import "StockAppHelper.h"
#import "UIView+LoadingView.h"

@implementation QuestionViewController
@synthesize questions=_questions;
@synthesize selectedIndexPaths;
@synthesize appService;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void)dealloc{
    self.questions = nil;
    self.selectedIndexPaths = nil;
    [self.appService cancleAllRequest];
    self.appService = nil;
    [super dealloc];
}
#pragma mark - View lifecycle

-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    [self.view showHUDLoadingView:NO];
    [[StockContext shareInstance] setFinishQuestions];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNeedUpdateRadarDateNotification object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    [[StockAppHelper shareInstance] showAlertViewWithMessage:@"提交发生错误！"];
    [self.view showHUDLoadingView:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *filePath = [[CommonUtil shareInstance] pathOfResouceInMainBundle:@"questions.plist"];
    self.questions = [NSArray arrayWithContentsOfFile:filePath];
    self.tableView.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.selectedIndexPaths = [NSMutableDictionary dictionary];
    UIBarButtonItem *send = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = send;
    [send release];
    self.appService = [[[StockAppService alloc] initWithDelegate:self] autorelease];
}
-(void)submit{
    if (selectedIndexPaths.count!=self.questions.count) {
        [[StockAppHelper shareInstance] showAlertViewWithMessage:@"请完成所有问题."];
        return;
    }
    NSMutableString *answers = [NSMutableString string];
    for (int i=0;i<self.questions.count;i++){
        NSIndexPath *indexPath = [selectedIndexPaths objectForKey:[NSString stringWithFormat:@"%d",i]];
        [answers appendFormat:@"%d",indexPath.row];
    }
    [appService submitAnswers:answers];
    [self.view showHUDLoadingView:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.questions = nil;
    self.selectedIndexPaths = nil;
    [self.appService cancleAllRequest];
    self.appService = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.questions.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{   
    NSDictionary *questionCategory = [self.questions objectAtIndex:section];
    NSArray *quests = [questionCategory objectForKey:@"children"];
    return quests.count;
}

-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35.0;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 35.0)];
    imageView.image = [UIImage imageNamed:@"segment_bg.png"];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 310.0, 35.0)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    NSDictionary *questionCategory = [self.questions objectAtIndex:section];
    label.text = [questionCategory objectForKey:@"title"];
    [imageView addSubview:label];
    [label release];
    return [imageView autorelease];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"QuestionCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.font = [UIFont systemFontOfSize:15.0];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.numberOfLines = 2;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    NSInteger index = [indexPath row];
    NSString *imageName = @"cellbg1.png";
    if (index%2==1) {
        imageName = @"cellbg2.png";
    }
    cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]] autorelease];
    NSDictionary *questionCategory = [self.questions objectAtIndex:indexPath.section];
    NSArray *quests = [questionCategory objectForKey:@"children"];
    
    cell.textLabel.text = [quests objectAtIndex:indexPath.row];
    NSIndexPath *selected = [selectedIndexPaths objectForKey:[NSString stringWithFormat:@"%d",indexPath.section]];
    NSString *acc = [selected isEqual:indexPath]?@"checkbox_selected.png":@"checkbox.png";
    cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:acc]] autorelease];
    
    return cell;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==3||(indexPath.section==1 && indexPath.row==2)) {
        return 60;
    }
    
    return 44.0;
}
#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *key = [NSString stringWithFormat:@"%d",indexPath.section];
    NSIndexPath *selected = [selectedIndexPaths objectForKey:key];
    if (selected) {
        if ([selected isEqual:indexPath]) {
            [selectedIndexPaths removeObjectForKey:key];
            cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox.png"]] autorelease];
        }else{
            cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox_selected.png"]] autorelease];
            UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:selected];
            lastCell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox.png"]] autorelease];
            
            [selectedIndexPaths setObject:indexPath forKey:key];
        }
    }else{
        [selectedIndexPaths setObject:indexPath forKey:key];
        cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox_selected.png"]] autorelease];
    }
}

@end
